package com.naiterui.common.jinshuju.config;

import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import com.naiterui.common.jinshuju.callback.handler.LogCallbackHandler;
import com.naiterui.common.jinshuju.callback.handler.WxmpCallbackHandler;
import com.naiterui.common.jinshuju.callback.router.CallbackRouter;
import com.naiterui.common.jinshuju.properties.JinshujuProperties;
import com.naiterui.common.jinshuju.service.JinshujuService;
import com.naiterui.common.jinshuju.service.impl.JinshujuServiceImpl;
import com.naiterui.common.jinshuju.util.RestTemplateUtil;
import com.naiterui.common.jinshuju.util.SpringContextUtil;

import lombok.AllArgsConstructor;

/**
 * @author gaoliangliang
 * @date 2019/10/20 4:50 下午
 * @since 1.0.0
 */
@Configuration
@AllArgsConstructor
public class JinshujuServiceAutoConfiguration {

    private final JinshujuProperties jinshujuProperties;
    private final LogCallbackHandler logCallbackHandler;
    private final WxmpCallbackHandler wxmpCallbackHandler;

    @Bean
    @ConditionalOnMissingBean
    public RestTemplate restTemplate() {
        return RestTemplateUtil.create();
    }

    @Bean
    ApplicationContextAware jinshujuContextAware() {
        return SpringContextUtil::init;
    }

    @Bean
    @ConditionalOnMissingBean
    public JinshujuService jinshujuService() {
        JinshujuService jinshujuService = new JinshujuServiceImpl();
        Map<String, JinshujuProperties.JinshujuConfig> configMap = jinshujuProperties.getConfigs()
                                                                                     .stream()
                                                                                     .collect(Collectors.toMap(
                                                                                             JinshujuProperties.JinshujuConfig::getUid, a -> a));
        jinshujuService.setJinshujuConfigStorage(configMap);
        return jinshujuService;
    }

    @Bean
    @ConditionalOnMissingBean
    public CallbackRouter callbackRouter(JinshujuService jinshujuService) {
        final CallbackRouter newRouter = new CallbackRouter(jinshujuService);

        // 所有金数据回调日志
        newRouter.rule().handler(this.logCallbackHandler).next();

        // 默认都走，需要特殊逻辑，项目内自定义微信填写,覆盖CallbackRouter类定义
        newRouter.rule().async(false).handler(this.wxmpCallbackHandler).end();

        return newRouter;
    }
}
